#include "mux_handler.h"
#include "thread_handler.h"
extern "C"
{
#include <libavformat/avformat.h>
}

using namespace std;

namespace lcf
{

    void MuxHandler::HandleTask(AVPacket *pkt)
    {
        pkts_.Push(pkt);
        Next(pkt);
    }

    void MuxHandler::Main()
    {
        muxer_.WriteHead();

        // 找到关键帧
        while (!isExit_)
        {
            std::unique_lock<std::mutex> lock(mtx_);
            AVPacket *pkt = pkts_.Pop();
            if (!pkt)
            {
                MSleep(1);
                continue;
            }
            if (pkt->stream_index == muxer_.VideoIndex() && pkt->flags & AV_PKT_FLAG_KEY) // 关键帧
            {
                muxer_.Write(pkt);
                av_packet_free(&pkt);
                break;
            }
            // 丢掉非视频关键帧
            av_packet_free(&pkt);
        }

        while (!isExit_)
        {
            unique_lock<mutex> lock(mtx_);
            AVPacket *pkt = pkts_.Pop();
            if (!pkt)
            {
                MSleep(1);
                continue;
            }

            muxer_.Write(pkt);
            cout << "W" << flush;

            av_packet_free(&pkt);
        }
        muxer_.WriteEnd();
        muxer_.SetContext(nullptr);
    }

    bool MuxHandler::Open(const char *url,
                          AVCodecParameters *videoPara,
                          AVRational *videoTimeBase,
                          AVCodecParameters *audioPara,
                          AVRational *audioTimeBase)
    {
        AVFormatContext *context = muxer_.Open(url, videoPara, audioPara);
        if (!context)
            return false;
        muxer_.SetContext(context);
        muxer_.SetSrcVideoTimeBase(videoTimeBase);
        muxer_.SetSrcAudioTimeBase(audioTimeBase);
        return true;
    }
}
